<?php
apf_require_class("Bll_BLL");
apf_require_class("Const_User");
apf_require_class("Const_Work");
apf_require_class("Const_Util");
apf_require_class("Const_BaseInfo");
apf_require_class("Const_Img");
class Bll_Portal_HomeData extends BLL {

    private $group = array(
        "techmgr" => array(
            "SHA008",//胡志明
            "SHB047",//张尔宁
            "SHB161",	//杜秋芳
            "SHD822",//常海松
            "SHE2687",//匡萃彪
            "SHC563",//徐震宇
            "SHF4329",//王道远
            "SHD1028",//马伟康
            "SHA015",//陈久发
            "SHD951",//解云
            "SHC291",//安红亮
            "SHD569",//赵鹏英
            "SHC301",//杨勇
            "SHD633",//王静
            "SHE2162",//冯李杰
            "SHC441",//胡家友
            "SHF3013",//韩文超
            "SHB098",//洪鑫锋
            "SHC300",//周枫
            "SHD615",//李洪波
            "SHD637",//郑紫薇
            "SHC476",//陈佳
            ),
        "mobldr" => array(
            "SHC515",	//杨杰
            "SUZE2456",	//王静
            "SHE1433",	//薛彬
            "SHE2475",	//曾伟铭
            "SHD633",	//王静
            "SHF3274",	//江军
            "SHA015",	//江军
            "SHF4170"	//曾华奕
            ),
    );

    /**
     * 通讯录搜索功能
     * @param array $query
     * 	e.g array(
     * 		"key" => "朱 新房",
     * 		"company" => "",
     * 		"unit"
     * 	)
     * @return unknown
     */
    public function search($query, $order = null, $limit = 100, $offset = 0){
        $kw = trim($query['kw']);
        if (empty($kw)){
            return array();
        }

        $_where = array();
        $cities = $this->get_property_bll()->get_city_list();
        $cities = $this->_build_key_value($cities,'city_id','city_name');
        $departments = $this->get_property_bll()->get_function_list();
        $departments = $this->_build_key_value($departments,'function_id','function_name');
        $divisions = $this->get_property_bll()->get_business_list();
        $divisions = $this->_build_key_value($divisions,'bu_id','bu_name');

        if (isset($this->group[strtolower($kw)])){
            $code_str = implode("','", $this->group[$kw]);
            $_where["user_code in('{$code_str}') and ?"] = 1;
        }else{
            //--是否按事业部过滤 - 事业
            $sy = trim($query['sy']);
            if (!empty($sy) && !empty($divisions[$sy])){
                $_where['bu_id'] = intval($sy);
            }
            //--是否按部门过滤
            $bm = trim($query['bm']);
            if (!empty($bm) && !empty($departments[$bm])){
                $_where['department_id'] = intval($bm);
            }
            //--是否按工作城市过滤
            $cs = trim($query['cs']);
            if (!empty($cs) && !empty($cities[$cs])){
                $_where['work_city_id'] = intval($cs);
            }

            $keywords = explode(" ", $kw);
            foreach ($keywords as $kw){
                $kw = mysql_escape_string($kw);
                $_temp_where = array();
                if (preg_match('/[\x81-\xFE][\x40-\xFE]/', $kw)){
                    //中文关键字
                    $_temp_where[] = "user_name like '%{$kw}%'";

                    //if($this->_is_no_search($kw)){
                        $_temp_where[] = "position_name like '%{$kw}%'";
                    //}
                }elseif (preg_match ('/^[0-9][0-9][0-9\-]+$/', $kw)){
                    //数字格式(座机|手机)
                    $_temp_where[] = "office_phone like '%$kw'";
                    $_temp_where[] = "cellphone = '$kw'";
                }elseif(preg_match ('/^[\w@._-]{3,}$/', $kw)) {
                    //英文字母(英文名|邮箱)
                    $_temp_where[] = "english_name like '%$kw%'";
                    $_temp_where[] = "office_mail like '%$kw%'";
                }else{
                    return array();
                }
                $_temp_where = implode(" OR ", $_temp_where);
                $_where["{$_temp_where} ?"] = '';
            }
        }
        $search_users = $this->get_search_user_dao()->find($_where, "", 0, 0);
        //分别获取员工，及员工上级的员工号
        $user_ids = $user_codes = array();
        foreach ($search_users as $user){
            $user_ids[] = $user['user_id'];
            $user_codes[] = $user['user_code'];
        }
        //users
        //$users = $this->get_user_bll()->get_user_by_ids($user_ids);
        $users = $search_users;unset($search_users);
        //jobs
        $works = $this->get_user_relation_bll()->get_user_job_info($user_ids);
        //获取考勤打卡信息
        $access_recode = $this->get_access_bll()->get_access_by_uids($user_codes);
        //获取员工基本信息-职级
        $p_leavel = $this->get_property_bll()->get_p_degree();
        $m_leavel = $this->get_property_bll()->get_m_degree();
        $_cs = array();
        $_bm = array();
        $_sy = array();
        foreach ($users as $key => $user){
            $user_id = $user['user_id'];
            $job_id = $works[$user_id]['job_info']['job_id'];
            $city_name = $cities[$user['work_city_id']];
            $department_name = $works[$user_id]['dep_info']["department_name"];
            $sy_name = $divisions[$works[$user_id]['dep_info']['bu_id']];
            //获取上级信息
            $_cs[$user['work_city_id']]= $city_name;
            $_bm[$works[$user_id]['dep_info']["function_id"]]= $departments[$user['department_id']];//$department_name;
            $_sy[$works[$user_id]['dep_info']['bu_id']]= $sy_name;
            $users[$key]['city_name'] = $city_name;
            $users[$key]['position_name'] = $works[$user_id]['job_info']['position_name'];
            $users[$key]['department_name'] = $sy_name.$department_name;
            $users[$key]['access_record'] = $access_recode[$user['user_code']] ? 1 : 0;
            $superior = $this->get_user_relation_bll()->get_director_direct_yes_new($user_id,$job_id,true,false);
            $users[$key]['superior_name'] = $superior['parent_name'] ? $superior['parent_name'] : "";
            $users[$key]['p_m_level'] = $user['m_level']?$m_leavel[$user['m_level']]['degree']:($user['p_level']?$p_leavel[$user['p_level']]['degree']:'');
            $users[$key]['headpic'] = Portal_Urls::build_user_pic_path($user['user_code'],Const_Img::PIC_SMALL);
        }
        if($users){
            $_cs = array_unique($_cs);
            $_cs = $this->_remove_kong($_cs);
            $_bm = array_unique($_bm);
            $_bm = $this->_remove_kong($_bm);
            $_sy = array_unique($_sy);
            $_sy = $this->_remove_kong($_sy);
        }
        $users = $this->_build_show_value($users);
        $result = array();
        $result["cs"] = $_cs ? $_cs : $cities;
        $result["bm"] = $_bm ? $_bm : $departments;
        $result["sy"] = $_sy ? $_sy : $divisions;
        $result["rs"] = $users;
        $result["md5key"]=md5(implode("",$users));
        return $result;
    }
    /**
     * 只允许部门且非技术部搜索
     * @param unknown_type $name
     * @return boolean
     */
    private function _is_no_search($name){
        $_yes_search_words = array('总裁','总经','人力资源部','财务部','产品部','市场部','运营部','销售部','BI部','客服部');
        $result = false;
        foreach($_yes_search_words as $val){
            if($name != str_replace($val, '', $name)){
                $result = true;
            }
        }
        return $result;
    }
    /**
     * 返回需要返回的数据
     *
     */
    function _build_show_value($users){
        $result = array();
        foreach($users as $user){
            $phone = ($user['office_phone'] && $user['office_phone_ex'])?'-':'';
            $result[] = array(
                    'real_name'=>$user['user_name'],
                    'headpic'=>$user['headpic'],
                    'english_name'=>$user['english_name'],
                    'user_code'=>$user['user_code'],
                    'department_name'=>$user['department_name'],
                    'city_name'=>$user['city_name'],
                    'position_name'=>$user['position_name'],
                    'p_m_level'=>$user['p_m_level'],
                    'office_mail'=>$user['office_mail'],
                    'office_phone'=>$user['office_phone'].$phone.$user['office_phone_ex'],
                    'office_phone_ex'=>$user['office_phone_ex'],
                    'superior_name'=>$user['superior_name'],
                    'cellphone'=>$user['cellphone'],
                    'access_record'=>$user['access_record'],
                    );
        }
        unset($users);
        return $result;
    }
    /**
     * 索引值
     * @param unknown_type $data
     * @param unknown_type $key
     * @param unknown_type $value
     */
    private function _build_key_value($data,$key,$value){
        $result = array();
        foreach($data as $one){
            $result[$one[$key]] = $one[$value];
        }
        unset($data);
        return $result;
    }
    private function _remove_kong($data){
        foreach($data as $index => $one){
            if(!$one){
                unset($data[$index]);
            }
        }
        return $data;
    }
    /**
     * 多个电话情况
     * @param unknown_type $users
     */
    private function _build_user_phone($users){
        foreach($users as $index=> $user){
            $users[$index]['telphone'] = str_replace('/', '<br/>', $user['telphone']);
        }
        return $users;
    }
    /**
     * 获取城市配置列表
     */
    public function get_cities(){
        return APF::get_instance()->get_config('cities');
    }

    /**
     * 获取事业部列表
     */
    public function get_divisions(){
        return APF::get_instance()->get_config('divisions');
    }

    /**
     * 获取部门列表
     */
    public function get_departments(){
        return APF::get_instance()->get_config('departments');
    }

    /**
     * 考勤打卡记录
     */
    private function get_access_bll(){
        if (!$this->access_bll || !$this->access_bll instanceof Bll_Attendance_AccessDayRecord){
            apf_require_class("Bll_Attendance_AccessDayRecord");
            $this->access_bll = new Bll_Attendance_AccessDayRecord();
        }
        return $this->access_bll;
    }
    /**
     * hroa user basic
     * @return Bll_Hr_User
     */
    private function get_user_bll(){
        if (!$this->user_bll || !$this->user_bll instanceof Bll_Hr_User){
            apf_require_class("Bll_Hr_User");
            $this->user_bll = new Bll_Hr_User();
        }
        return $this->user_bll;
    }
    /**
     * user_relation
     * @return Bll_Hr_User
     */
    private function get_user_relation_bll(){
        if (!$this->user_relation_bll || !$this->user_relation_bll instanceof Bll_Hr_UserRelation){
            apf_require_class("Bll_Hr_UserRelation");
            $this->user_relation_bll = new Bll_Hr_UserRelation();
        }
        return $this->user_relation_bll;
    }
    /**
     * 参数
     * @return Bll_Hr_Property
     */
    private function get_property_bll(){
        if (!$this->property_bll || !$this->property_bll instanceof Bll_Hr_Property){
            apf_require_class("Bll_Hr_Property");
            $this->property_bll = new Bll_Hr_Property();
        }
        return $this->property_bll;
    }
    /**
     * 使用考勤系统数据库中的
     * return Dao_Attendance_UserInfo
     */
    private function get_user_dao(){
        return $this->get_dao('Dao_Attendance_UserInfo');
    }
    /**
     * 使用HR-OA系统数据库中的
     * return Dao_Hr_User
     */
    private function get_basic_user_dao(){
        return $this->get_dao('Dao_Hr_User');
    }
    /**
     * 使用HR-OA系统数据库中的
     * return Dao_Hr_User
     */
    private function get_search_user_dao(){
        return $this->get_dao('Dao_Portal_UserSearch');
    }
    public function update_search_user($id,$data){
        if(!$id || !is_numeric($id)){
            return ;
        }
        $this->get_search_user_dao()->update_by_id($id,$data);
    }

}